package com.ovo.dailypayaccount.controller;

import com.ovo.dailypayaccount.entity.PayData;
import com.ovo.dailypayaccount.entity.PayDataClassify;
import com.ovo.dailypayaccount.entity.PayDataOfWeek;
import com.ovo.dailypayaccount.entity.UserInfo;
import com.ovo.dailypayaccount.service.BasePayDataService;
import com.ovo.dailypayaccount.service.BaseUserService;
import com.ovo.dailypayaccount.utils.PayDataHandleUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class DailyPayDataController {
	Logger log = LoggerFactory.getLogger(DailyPayDataController.class);
	@Autowired
	private BaseUserService userService;
	@Autowired
	private BasePayDataService payDataService;
	
	@RequestMapping(value = "/toSaveData", method = RequestMethod.POST)
	public void toSaveData(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String[] items = request.getParameterValues("pay_item");
		String[] amounts = request.getParameterValues("pay_amount");
		String retime = request.getParameter("retime");//补录时间
		PayData pd = new PayData();
		Cookie[]cookies = request.getCookies();
		for(Cookie cookie:cookies) {
			if(cookie.getName().equals("userId")) {
				pd.setUserId(Integer.valueOf(cookie.getValue()));
			}
		}
				
		StringBuffer payItems = new StringBuffer();
		BigDecimal amountSum = new BigDecimal(0);
		for(int i=0; i<items.length;i++) {
			if(StringUtils.isNotEmpty(items[i])&&StringUtils.isNotEmpty(amounts[i])) {
				payItems.append("\""+items[i]+"\":\""+amounts[i]+"\",");
				BigDecimal amount = BigDecimal.valueOf(Double.valueOf(amounts[i]));
				amountSum = amountSum.add(amount);
			}
		}
		log.info(">>>>>>>保存数据："+payItems.toString());
		pd.setPayItems("{"+payItems.toString().substring(0, payItems.length()-1)+"}");
		pd.setPayAmountSum(amountSum);
		pd.setPayDate(new Date());
		if(StringUtils.isNotBlank(retime)) {
			Calendar calendar2= Calendar.getInstance();
			calendar2.set(Calendar.YEAR,Integer.parseInt(retime.substring(0,4)));
			calendar2.set(Calendar.MONTH,Integer.parseInt(retime.substring(5,7))-1);
			calendar2.set(Calendar.DATE,Integer.parseInt(retime.substring(8)));
			pd.setPayDate(calendar2.getTime());
		}
		pd.setCreateTime(new Date());
		payDataService.addPayData(pd);
		response.sendRedirect("reloadIndex");
	}
	/**
	 * 获取当周数据
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/toGetPayDataWeek")
	public ModelMap toGetPayDataWeek(HttpServletRequest request, HttpServletResponse response) {
		log.info(">>>>>>>获取本周数据。");
		ModelMap result = new ModelMap();
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		// 判断要计算的日期是否是周日，如果是则减一天计算周六的，否则会出问题，计算到下一周去了
		int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
		if (1 == dayOfWeek) {
			cal.add(Calendar.DAY_OF_MONTH, -7);
		}
		cal.setFirstDayOfWeek(Calendar.MONDAY);// 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
		cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - dayOfWeek);// 根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
		String payDate = sdf.format(cal.getTime());		
		Cookie[]cookies = request.getCookies();
		UserInfo user = null;
		String userId = null;
		if(cookies!=null) {	
			for(Cookie cookie:cookies) {
				if(cookie.getName().equals("userId")) {
					userId = cookie.getValue();
				}
			}
			if(userId!=null) {
				user = userService.getUserById(Integer.valueOf(userId));
				Map<String,String>params = new HashMap<>();
				params.put("userId", user.getId().toString());
				params.put("payDate", payDate);
				List<PayData> list = payDataService.getDataOfWeek(params);
				BigDecimal sumpay = payDataService.getSumPayDataOfWeek(params);
				result.addAttribute("sumPayWeek", sumpay);
				//获取分类消费数
				List<PayDataClassify> pieDataWeek = PayDataHandleUtil.getClassifyPayData(list);
				StringBuffer buffer = new StringBuffer();
				for(PayDataClassify pdc:pieDataWeek) {
					buffer.append(pdc.getItem()+" : "+pdc.getAmount()+" ,");
				}
				result.addAttribute("distributeData_week", buffer.toString().substring(0,buffer.length()-1));
				List<PayDataOfWeek> resultList =new ArrayList<>();
				for(PayData pd:list) {
					Date date2 = pd.getPayDate();
					cal.setTime(date2);
					int rank = cal.get(Calendar.DAY_OF_WEEK)-1;
					PayDataOfWeek pw = new PayDataOfWeek();
					pw.setPayAmountSum(pd.getPayAmountSum().toString());
					switch(rank) {
					case 0:pw.setPayDate("日");
					break;
					case 1:pw.setPayDate("一");
					break;
					case 2:pw.setPayDate("二");
					break;
					case 3:pw.setPayDate("三");
					break;
					case 4:pw.setPayDate("四");
					break;
					case 5:pw.setPayDate("五");
					break;
					case 6:pw.setPayDate("六");	
					}
					String rank2 = pw.getPayDate();
					int ck = checkCopyData(resultList,rank2);
					if(ck!=-1) {
						PayDataOfWeek copy_pw = resultList.get(ck);
						BigDecimal sumpay2 = BigDecimal.valueOf(Double.parseDouble(copy_pw.getPayAmountSum()))
								.add(pd.getPayAmountSum());
						copy_pw.setPayAmountSum(sumpay2.toString());
					}else {
						resultList.add(pw);
					}
				}
				result.addAttribute("pieDataWeek", pieDataWeek);
				result.addAttribute("resultList", resultList);
			}
		}
		
		return result;
	}
	/**
	 * 检查是否有补录进去的重复日期数据，返回已存在的日期，求和去重
	 * @param resultList
	 * @param rank2
	 * @return
	 */
	public int checkCopyData(List<PayDataOfWeek> resultList,String rank2) {
		int rank = 0;
		if(null!=resultList&&resultList.size()>1) {
			for(PayDataOfWeek dw:resultList) {
				if(dw.getPayDate().equals(rank2)) {
					return rank;
				}
				rank++;
			}
		}
		return -1;
	}
	/**
	 * 获取当月数据
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/toGetPayDataMonth")
	public ModelMap toGetPayDataMonth(HttpServletRequest request, HttpServletResponse response) {
		log.info(">>>>>>>获取本月数据。");
		ModelMap result = new ModelMap();
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.DAY_OF_MONTH,1);
		calendar.add(Calendar.MONTH, 0);
		String payDate = sdf.format(calendar.getTime());		
		Cookie[]cookies = request.getCookies();
		UserInfo user = null;
		String userId = null;
		if(cookies!=null) {	
			for(Cookie cookie:cookies) {
				if(cookie.getName().equals("userId")) {
					userId = cookie.getValue();
				}
			}
			if(userId!=null) {
				user = userService.getUserById(Integer.valueOf(userId));
				Map<String,String>params = new HashMap<>();
				params.put("userId", user.getId().toString());
				params.put("payDate", payDate);			
				List<PayData> list = payDataService.getDataOfWeek(params);
				//获取本周总消费数
				BigDecimal sumpay = payDataService.getSumPayDataOfMonth(params);
				result.addAttribute("sumPayMonth", sumpay);
				//获取分类消费数
				List<PayDataClassify> pieDataMonth = PayDataHandleUtil.getClassifyPayData(list);
				StringBuffer buffer = new StringBuffer();
				for(PayDataClassify pdc:pieDataMonth) {
					buffer.append(pdc.getItem()+" : "+pdc.getAmount()+" ,");
				}
				result.addAttribute("distributeData_month", buffer.toString().substring(0,buffer.length()-1));
				
				List<PayDataOfWeek> resultList =new ArrayList<>();
				SimpleDateFormat sdf2 = new SimpleDateFormat("dd");
				for(PayData pd:list) {
					PayDataOfWeek pw = new PayDataOfWeek();
					pw.setPayAmountSum(pd.getPayAmountSum().toString());
					pw.setPayDate(sdf2.format(pd.getPayDate()));
					String rank2 = pw.getPayDate();
					int ck = checkCopyData(resultList,rank2);
					if(ck!=-1) {
						PayDataOfWeek copy_pw = resultList.get(ck);
						BigDecimal sumpay2 = BigDecimal.valueOf(Double.parseDouble(copy_pw.getPayAmountSum()))
								.add(pd.getPayAmountSum());
						copy_pw.setPayAmountSum(sumpay2.toString());
					}else {
						resultList.add(pw);
					}			
				}
				result.addAttribute("pieDataMonth", pieDataMonth);
				result.addAttribute("resultList", resultList);				
				}
			}
		return result;
	}
	
	/**
	 * 获取指定日期数据
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/toGetPayDataForDate")
	public ModelMap toGetPayDataForDate(HttpServletRequest request, HttpServletResponse response) {
		ModelMap result = new ModelMap();
		String beginDate = request.getParameter("beginDate");
		String endDate = request.getParameter("endDate");
		log.info(">>>>>>>获取指定起始日期："+beginDate+"，截止日期："+endDate+"的数据。");
		if(StringUtils.isBlank(beginDate)||StringUtils.isBlank(endDate)) {
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
			Calendar calendar1= Calendar.getInstance();
			calendar1.setTime(date);
			endDate = sdf.format(calendar1.getTime());
			calendar1.add(Calendar.DATE, -30);
			beginDate = sdf.format(calendar1.getTime());
		}else {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
			Calendar calendar2= Calendar.getInstance();
			calendar2.set(Calendar.YEAR,Integer.parseInt(beginDate.substring(0,4)));
			calendar2.set(Calendar.MONTH,Integer.parseInt(beginDate.substring(5,7))-1);
			calendar2.set(Calendar.DATE,Integer.parseInt(beginDate.substring(8)));
			beginDate = sdf.format(calendar2.getTime());
			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
			calendar2.set(Calendar.YEAR,Integer.parseInt(endDate.substring(0,4)));
			calendar2.set(Calendar.MONTH,Integer.parseInt(endDate.substring(5,7))-1);
			calendar2.set(Calendar.DATE,Integer.parseInt(endDate.substring(8)));
			endDate = sdf2.format(calendar2.getTime());
		}
		
		Cookie[]cookies = request.getCookies();
		UserInfo user = null;
		String userId = null;
		if(cookies!=null) {	
			for(Cookie cookie:cookies) {
				if(cookie.getName().equals("userId")) {
					userId = cookie.getValue();
				}
			}
			if(userId!=null) {
				user = userService.getUserById(Integer.valueOf(userId));
				Map<String,String>params = new HashMap<>();
				params.put("userId", user.getId().toString());
				params.put("beginDate", beginDate);
				params.put("endDate", endDate);	
				List<PayData> list = payDataService.getDataOfDate(params);
				//获取本周总消费数
				BigDecimal sumpay = payDataService.getSumPayDataOfDate(params);
				result.addAttribute("sumPayDate", sumpay);
				//获取分类消费数
				List<PayDataClassify> pieDataDate = PayDataHandleUtil.getClassifyPayData(list);
				StringBuffer buffer = new StringBuffer();
				for(PayDataClassify pdc:pieDataDate) {
					buffer.append(pdc.getItem()+" : "+pdc.getAmount()+" ,");
				}
				result.addAttribute("distributeData_date", buffer.toString().substring(0,buffer.length()-1));
				
				List<PayDataOfWeek> resultList =new ArrayList<>();
				SimpleDateFormat sdf3 = new SimpleDateFormat("dd");
				for(PayData pd:list) {
					PayDataOfWeek pw = new PayDataOfWeek();
					pw.setPayAmountSum(pd.getPayAmountSum().toString());
					pw.setPayDate(sdf3.format(pd.getPayDate()));
					String rank2 = pw.getPayDate();
					int ck = checkCopyData(resultList,rank2);
					if(ck!=-1) {
						PayDataOfWeek copy_pw = resultList.get(ck);
						BigDecimal sumpay2 = BigDecimal.valueOf(Double.parseDouble(copy_pw.getPayAmountSum()))
								.add(pd.getPayAmountSum());
						copy_pw.setPayAmountSum(sumpay2.toString());
					}else {
						resultList.add(pw);
					}			
				}
				result.addAttribute("pieDataDate", pieDataDate);
				result.addAttribute("resultList", resultList);				
				}
			}
		return result;
	}

}
